package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type firmwaresRecord struct {
	iFirmwaresRecord store.IFirmwaresRecord
}

var FirmwaresRecord = &firmwaresRecord{
	iFirmwaresRecord: postgres.FirmwaresRecord,
}

func (a *firmwaresRecord) init() func() {
	return func() {}
}

func (a *firmwaresRecord) onEvent(*event.Data) {}

// Create 创建
func (a *firmwaresRecord) Create(ctx context.Context, in *model.FirmwaresRecordCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildFirmwaresRecord(in)
	_, err = a.iFirmwaresRecord.Create(ctx, c)
	return err
}

// Update 更新
func (a *firmwaresRecord) Update(ctx context.Context, in *model.FirmwaresRecordUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.FirmwareId != nil {
		dict["firmware_id"] = in.FirmwareId
	}

	if in.TacticsId != nil {
		dict["tactics_id"] = in.TacticsId
	}

	if in.Version != nil {
		dict["version"] = in.Version
	}

	if in.EbikesType != nil {
		dict["ebikes_type"] = in.EbikesType
	}

	if in.FirmwaresName != nil {
		dict["firmwares_name"] = in.FirmwaresName
	}

	// do other update here
	return a.iFirmwaresRecord.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *firmwaresRecord) Delete(ctx context.Context, in *model.FirmwaresRecordDeleteRequest) error {
	return a.iFirmwaresRecord.Delete(ctx, in.Id)
}

// List 列表查询
func (a *firmwaresRecord) List(ctx context.Context, in *model.FirmwaresRecordListRequest) (*model.FirmwaresRecordListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.FirmwaresRecord
		out   = &model.FirmwaresRecordListResponse{}
	)

	if total, list, err = a.iFirmwaresRecord.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.FirmwaresRecordsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *firmwaresRecord) Find(ctx context.Context, in *model.FirmwaresRecordInfoRequest) (*model.FirmwaresRecordInfo, error) {
	var (
		err  error
		data *entity.FirmwaresRecord
		out  = &model.FirmwaresRecordInfo{}
	)

	if data, err = a.iFirmwaresRecord.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.FirmwaresRecordEntityToDto(data)
	return out, nil
}

// buildFirmwaresRecord 构建创建数据现场
func buildFirmwaresRecord(in *model.FirmwaresRecordCreateRequest) *entity.FirmwaresRecord {
	// todo: check the entity is required
	return &entity.FirmwaresRecord{

		FirmwareId: in.FirmwareId,

		TacticsId: in.TacticsId,

		Version: in.Version,

		EbikesType: in.EbikesType,

		FirmwaresName: in.FirmwaresName,

		CreatedAt: time.Now().Unix(),
	}
}
